package cloudPayAdmin.util;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.mts.model.v20140618.SearchPipelineRequest;
import com.aliyuncs.mts.model.v20140618.SearchPipelineResponse;
import com.aliyuncs.mts.model.v20140618.SubmitSnapshotJobRequest;
import com.aliyuncs.mts.model.v20140618.SubmitSnapshotJobResponse;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.io.FilenameUtils;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.internal.OSSUtils;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectResult;

public class AliyunUtil {

	// endpoint以杭州为例，其它region请按实际情况填写
	public static String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";

	// accessKey请登录https://ak-console.aliyun.com/#/查看
	//public static String accessKeyId = "LTAIEaEhEg9H9B7B";
	//public static String accessKeySecret = "VuKehxiM8wGSAJAr4EtJ6Joq2BIExD";
	
	public static String accessKeyId = "LTAIWLCSvFR9BfBi";
	public static String accessKeySecret = "lRLSwItZX4hIRqFbo8exZrf4jL7fZU";

	//public static final String PRIVATE_BUCKETNAME = "yctapp";
	public static final String PUBLIC_BUCKETNAME = "scut-traffic";

	private static OSSClient ossClient = null;

	static {

		try {
		/*	// 创建ClientConfiguration实例
			ClientConfiguration conf = new ClientConfiguration();

			// 配置代理为本地8080端口
			conf.setProxyHost("10.240.19.65");
			conf.setProxyPort(8888);*/

			// 创建OSS客户端
			//ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf);
			 ossClient = new OSSClient(endpoint, accessKeyId,
			 accessKeySecret);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 上传图片到阿里云OSS
	 * 
	 * @param env
	 * @param bucketName
	 * @param picPath
	 */
	public static void uploadFile(String bucketName, String picPath, String filename) {
		// 上传文件
		// boolean f = new File(picPath).exists();
		ossClient.putObject(bucketName, filename, new File(picPath));
	}

	public static void uploadFile(String bucketName, File file, String filename) {
		ossClient.putObject(bucketName, filename, file);  
	}
	
	public static void uploadFile(String bucketName, InputStream inputstream, String filename) {
		ossClient.putObject(bucketName, filename, inputstream);
	}

	/**
	 * @param bucketName
	 *            存储空间名 "yctapp"
	 * @param picPath
	 *            图片路径，包括图片名称 "card/hello.jpg"
	 * @param style
	 *            图片展示模式, 比如 缩放 image/resize,m_fixed,w_200,h_100
	 * @return
	 * @minutes 过期时间N分钟
	 */
	public static String getPicUrl(String bucketName, String picPath, String style, long minutes) {
		try {
			Date expiration = new Date(new Date().getTime() + 1000 * 60 * minutes);
			GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, picPath, HttpMethod.GET);
			req.setExpiration(expiration);
			if (style != null && !style.equals(""))
				req.setProcess(style);

			URL signedUrl = ossClient.generatePresignedUrl(req);
			return signedUrl.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}

	}

	/**
	 * 获取公共全下的bucket的url
	 * 
	 * @param bucketName
	 * @param picPath
	 * @param ssl
	 * @return
	 */
	public static String getPublicUrl(String bucketName, String picPath, boolean ssl) {
		StringBuilder url = new StringBuilder();
		if (ssl == Boolean.TRUE) {
			url.append("https://");
		} else {
			url.append("http://");
		}

		url.append(bucketName).append(".").append(endpoint.replace("http://", "")).append("/").append(picPath);

		return url.toString();
	}

	/**
	 * 生成上传阿里云oss的key
	 * 
	 * @param prefix
	 *            路径的前缀 如何 activity/111.jpg activity就是前缀
	 * @param fileName
	 *            文件的名字 如 111.jpg
	 * @return
	 */
	public static String generateAliyunKey(String prefix, String fileName) {
		return prefix + "/" + System.currentTimeMillis() + "." + FilenameUtils.getExtension(fileName);
	}

	public static void main1(String args[]) {
		// String url = getPicUrl( "yctapp", "card/TestPicttt.jpg",
		// "image/resize,m_fixed,w_200,h_100", 30);
//		uploadFile(PUBLIC_BUCKETNAME, "D:\\2156.mp4", "2156.mp4");

		snapshotJob();

		// 列举Object
		ObjectListing objectListing = ossClient.listObjects(PUBLIC_BUCKETNAME);
		List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
		for (OSSObjectSummary s : sums) {
			System.out.println("\t" + s.getKey());
		}
		// String url = getPublicUrl("yctappext","222.jpg",Boolean.FALSE);
	}

	public static OSSClient getOssClient() {
		return ossClient;
	}

	private static JSONObject generateSnapshotConfig(String osslocation, String outputbucket,
													 String outputobject, String time, String interval, String num
//                                                    , String frametype, String width, String height
	) {
		JSONObject snapshotConfig = new JSONObject();
		JSONObject output = generateSnapshotInput(osslocation, outputbucket, outputobject);
		snapshotConfig.put("OutputFile", output);
		snapshotConfig.put("Time", time);
		snapshotConfig.put("Interval", interval);
		snapshotConfig.put("Num", num);
//        snapshotConfig.put("FrameType", frametype);
//        snapshotConfig.put("Width", width);
//        snapshotConfig.put("Height", height);
		return snapshotConfig;
	}


	private static JSONObject generateSnapshotInput(String ossLocation,
													String inputBucket, String inputObject) {
		JSONObject input = new JSONObject();
		input.put("Location", ossLocation);
		input.put("Bucket", inputBucket);
		input.put("Object", inputObject);
		return input;
	}

	public static void snapshotJob(){

		String region = "cn-shenzhen";
		String accessKeyId = "LTAIWLCSvFR9BfBi";
		String accessKeySecret = "lRLSwItZX4hIRqFbo8exZrf4jL7fZU";
//        String pipelineId = "<pipelineId>";
		String inputBucket = "scut-traffic";
		String ossLocation = "oss-cn-shenzhen";
		String inputObject = "2156.mp4";
		String outputBucket = "scut-traffic";
		String outputObject = "{Count}.jpg";
		String time = "0";
		String interval = "1";
		String num = "10";
//        String frameType = "<frameType>";
//        String width = "<width>";
//        String height = "<height>";
		DefaultProfile profile = DefaultProfile.getProfile(region, accessKeyId, accessKeySecret);
		DefaultAcsClient client = new DefaultAcsClient(profile);
		try {
			SubmitSnapshotJobRequest request = new SubmitSnapshotJobRequest();
			request.setInput(generateSnapshotInput(ossLocation, inputBucket, inputObject).toJSONString());
			request.setSnapshotConfig(generateSnapshotConfig(ossLocation, outputBucket, outputObject, time,
					interval, num).toJSONString());
//
			SearchPipelineRequest searchPipelineRequest = new SearchPipelineRequest();
			// 如果出错，可能会抛出ClientException或ServerException异常
			SearchPipelineResponse searchPipelineResponse = client.getAcsResponse(searchPipelineRequest);
			List<SearchPipelineResponse.Pipeline> pipelines = searchPipelineResponse.getPipelineList();
			for (SearchPipelineResponse.Pipeline pipeline : pipelines) {
				System.out.println("pipeline id:" + pipeline.getId() + ", name:" + pipeline.getName() + ", state:" + pipeline.getState());
				request.setPipelineId(pipeline.getId());
				SubmitSnapshotJobResponse response = client.getAcsResponse(request);
				SubmitSnapshotJobResponse.SnapshotJob job = response.getSnapshotJob();
				System.out.println(job.getId());
			}

		} catch (ClientException e) {
			System.out.println(e.getErrorMessage());
		} catch (
				Exception e)
		{
			System.out.println(e.getMessage());
		}
	}
}
